<template>
  <div>
    <el-row>
      <el-col style="margin-top: 30px">
        <el-button
          type="primary"
          plain
          style="width: 20%"
          @click="bt_1()"
          :class="{ 'active-button': reply === 1 }"
          >入库绑定</el-button
        >
        <el-button
          type="primary"
          plain
          style="width: 20%"
          @click="bt_2()"
          :class="{ 'active-button': reply === 2 }"
          >入库绑定</el-button
        >
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
          v-if="Data!=null"
        >
          <el-table-column
            prop="id"
            label="ID"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="messagetype"
            label="留言类型"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="content"
            label="留言内容"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="createtime"
            label="留言时间"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editGoods(scope.row)"
                >回复</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="delBerbak(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <el-dialog
        title="留言回复"
        v-model="dialogFormVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form :model="form" label-position="right">
          <el-form-item label="留言类型:" label-width="100px">
            <el-input v-model="form.messagetype" disabled></el-input>
          </el-form-item>
          <el-form-item label="留言内容" label-width="100px">
            <el-input v-model="form.content" disabled></el-input>
          </el-form-item>

          <el-form-item label="新增留言回复" label-width="100px">
            <el-input type="textarea" v-model="back"></el-input>
          </el-form-item>

          <el-card class="box-card1">
            <div slot="header" class="clearfix">
              <span>往期回复</span>
            </div>
            <div
              v-for="(item, index) in back_List"
              :key="index"
              class="text item"
            >
              {{ item.content }}
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                circle
                style="float: right"
                @click="del_write(item.id)"
              ></el-button>
            </div>
          </el-card>
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin-top: 10px">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeMount } from "vue";
import apiService from "@/services/apiService";
import { v4 as uuidv4 } from "uuid";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Bind"
});

//表格数据
const Data = ref<any>([]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const reply = ref<number>(1); //当前显示

//切换按钮
const bt_1 = () => {
  reply.value = 1;
  console.log(reply.value);
  GetList();
};
const bt_2 = () => {
  reply.value = 2;
  console.log(reply.value);
  GetList_2();
};
//获取未回复表单数据
const GetList = () => {
  const params = {
    msgid: "PagingFindLeaveMsg",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value,
      userid: "",
      iswritemsgs: "未回复"
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      let arr = res.data.body.leavemsgs;
      for (let i = 0; i < arr.length; i++) {
        arr[i].createtime =
          arr[i].createtime.slice(0, 10) + " " + arr[i].createtime.slice(11);
      }
      Data.value = arr;
      Total.value = res.data.body.recordnumber;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};

//获取已回复表单数据
const GetList_2 = () => {
  const params = {
    msgid: "PagingFindLeaveMsg",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value,
      userid: "",
      iswritemsgs: "已回复"
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      let arr = res.data.body.leavemsgs;
      for (let i = 0; i < arr.length; i++) {
        arr[i].createtime =
          arr[i].createtime.slice(0, 10) + " " + arr[i].createtime.slice(11);
      }
      Data.value = arr;
      Total.value = res.data.body.recordnumber;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};

// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  if (reply.value == 1) {
    console.log("未回复");
    GetList();
  } else {
    console.log("已回复");
    GetList_2();
  }
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
};

//删除
const delBerbak = (row: any) => {
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "RemoveLeaveMsg",
        token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
        seq: uuidv4(),
        body: {
          leavemsgid: row.id
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          if (reply.value == 1) {
            GetList();
          } else {
            GetList_2();
          }
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

//编辑回复
const dialogFormVisible = ref(false);
const form = reactive({
  messagetype: "",
  content: "",
  id: ""
});
const back = ref("");
const back_List = ref([]);
const editGoods = (row: any) => {
  console.log("回复");
  form.messagetype = row.messagetype;
  form.content = row.content;
  form.id = row.id;
  back_List.value = row.writemsgs;
  dialogFormVisible.value = true;
};
//删除回复
const del_write = id => {
  ElMessageBox.confirm("确定删除该留言吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "RemoveWriteMsg",
        token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
        seq: uuidv4(),
        body: {
          writemsgid: id
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除回复成功"
          });
          FindWriteMsgByLeavemsg();
          GetList();
          GetList_2();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};
//根据留言ID查询留言
const FindWriteMsgByLeavemsg = () => {
  const params = {
    msgid: "FindWriteMsgByLeavemsgID",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      leavemsgid: form.id
    }
  };
  apiService.post("", params).then((res: any) => {
    console.log(res);
    if (res.data.code == 200) {
      back_List.value = res.data.body.writemsgs;
    }
  });
};
//回复按钮
const submit = () => {
  ElMessageBox.confirm("确定添加回复吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const utcDate = ref<any>();
      var date = new Date();
      utcDate.value = new Date(
        date.getTime() + date.getTimezoneOffset() * 60 * 1000
      );
      console.log(utcDate.value);

      const params = {
        msgid: "InsertWriteMsg",
        token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
        seq: uuidv4(),
        body: {
          leavemsgid: form.id,
          content: back.value,
          messagetypeid: 2,
          // fileid:'',
          createtime: utcDate.value
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "回复成功"
          });
          if (reply.value == 1) {
            GetList();
          } else {
            GetList_2();
          }
          back.value = "";
          dialogFormVisible.value = false;
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消回复"
      });
      dialogFormVisible.value = false;
    });
};
//关闭弹窗
const handleClose = (done: () => void) => {
  // ElMessageBox.confirm("确认关闭?")
  //   .then(() => {
  back.value = "";
  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};

onMounted(() => {
  GetList();
});
</script>

<style lang="scss" scoped>
.active-button {
  background-color: #409eff; /* 设置按钮激活时的背景颜色 */
  color: white; /* 设置按钮激活时的文字颜色 */
}
</style>
